package com.kqb.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kqb.common.domain.AjaxResult;

import com.kqb.common.domain.page.PageResult;
import com.kqb.mapper.RoleMapper;

import com.kqb.mapper.RolePermissionRelMapper;
import com.kqb.pojo.Permission;
import com.kqb.pojo.Role;

import com.kqb.pojo.RolePermissionRelKey;
import com.kqb.pojo.dto.RoleDto;
import com.kqb.service.IRoleService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * @author 杉果树皮
 * @date 2025/2/17 20:11
 * @description:
 */
@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;


    @Autowired
    private RolePermissionRelMapper rolePermissionRelMapper;

    @Override
    public AjaxResult deleteById(Integer id) {
        if (roleMapper.select(id) == null) {
            return AjaxResult.error("删除角色失败,角色信息不存在");
        }
        return roleMapper.delete(id) == 0 ? AjaxResult.error("删除角色失败") : AjaxResult.success("删除角色成功");
    }

    @Override
    @Transactional
    public AjaxResult save(RoleDto roleDTO) {
        Role role = new Role();
        roleDTO.getPermissions().forEach((v) -> {
            if ("0".equals(v.getIsEnabled())) {
                role.getPermissions().add(v);
            }
        });
        role.setName(roleDTO.getName());
        role.setIsEnabled(roleDTO.getIsEnabled());
        /**
         * 将角色信息添加到角色表
         */
        int save = roleMapper.save(role);

        for (Permission permission : role.getPermissions()) {
            rolePermissionRelMapper.saveRolePermission(new RolePermissionRelKey(role.getId(), permission.getId()));
        }

        return save == 0 ? AjaxResult.error("添加角色失败") : AjaxResult.success("添加角色成功");
    }

    @Override
    public AjaxResult selectByPage(RoleDto roleDTO) {
        PageHelper.startPage(roleDTO.getPageNum(), roleDTO.getPageSize());
        List<Role> roles = roleMapper.queryByPage(roleDTO);
        PageInfo<Role> rolePageInfo = new PageInfo<>(roles);
        return AjaxResult.success(new PageResult(roleDTO.getPageNum(), roleDTO.getPageSize(), rolePageInfo.getTotal(), rolePageInfo.getList()));

    }

    @Override
    public AjaxResult selectAll() {
        return AjaxResult.success(roleMapper.selectAll());
    }
}
